package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.common.Constants;
import com.bdqn.common.PageSupport;
import com.bdqn.pojo.Supplier;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SupplierService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/supplier")
public class SupplierController {
    private static final Logger logger = Logger.getLogger(UserController.class);

    @Resource
    private SupplierService supplierService;

    @GetMapping("/list")
    public String list(Model model, String querySupCode, String querySupName, @RequestParam(defaultValue = "1") Integer pageIndex) {
//        设置参数
        Supplier supplier = new Supplier();
        supplier.setSupCode(querySupCode);
        supplier.setSupName(querySupName);

        PageSupport page = new PageSupport();
        page.setCurrentPageNo(pageIndex);
        page.setTotalCount(supplierService.count(supplier));
        List<Supplier> pageList = supplierService.getPageList(supplier, page);

        model.addAttribute("querySupCode", querySupCode);
        model.addAttribute("querySupName", querySupName);
        model.addAttribute("pageIndex", pageIndex);

        model.addAttribute("supplierList", pageList);
        model.addAttribute("page", page);
        return "/supplier/list";
    }

    @GetMapping("/view/{supId}")
    public String view(Model model, @PathVariable("supId") Integer supId) {
        Supplier supplier = supplierService.queryId(supId);
        model.addAttribute("supplier", supplier);
        return "supplier/view";
    }

    @ResponseBody
    @GetMapping("/simpleList")
    public Object simpleList() {
        List<Supplier> list = supplierService.getSupName();//初始化供货商信息
        return JSON.toJSONString(list);
    }

    @GetMapping("/toUpdate/{supId}")
    public String toUpdate(Model model, @PathVariable("supId") Integer supId) {
        Supplier supplier = supplierService.queryId(supId);
        model.addAttribute("supplier", supplier);
        return "supplier/update";
    }

    @PostMapping("/update")
    public String doUpdate(HttpSession session, Supplier supplier) {
        supplier.setUpdatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
        boolean update = supplierService.update(supplier);
        return "redirect:/supplier/list";
    }

    @ResponseBody
    @DeleteMapping("del/{supId}")
    public String delete(@PathVariable("supId") Integer supId){
        Map<String,Object> map = new HashMap<>();
        Supplier supplier = supplierService.queryId(supId);
        boolean delete = supplierService.delete(supId);
        if (supplier == null){
            map.put("delResult","notexist");
            return JSON.toJSONString(map);
        }
        map.put("delResult",delete ? "true":"false");
        return JSON.toJSONString(map);
    }

    @GetMapping("/toAdd")
    public String toAdd(){
        return "supplier/add";
    }

    /**
     * 添加用户（带文件上传）
     */
    @PostMapping("/add")
    public String add(HttpServletRequest request, HttpSession session, Supplier supplier,
                      @RequestParam(value = "companyLicPic1", required = false) MultipartFile companyLicPic,
    @RequestParam(value = "orgCodePic1", required = false) MultipartFile orgCodePic) {

        System.out.println(companyLicPic + "=============================================");
        System.out.println(orgCodePic + "=============================================");
        // 从Session中获取当前登录用户
        SysUser loginUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        // 设置现在新添加的用户是由哪个账号创建的（填充数据库中createdUserId字段）
        supplier.setCreatedUserId(loginUser.getId());

        // 文件上传到服务器的真实位置
        String uploadPath = session.getServletContext().getRealPath(Constants.UPLOAD_PATH);

        // 上传企业营业执照
        if (companyLicPic != null) {
            String companyLicPicPath = multipartFileUpload(uploadPath, request, companyLicPic);
            if (companyLicPicPath == null) {
                String uploadFileError = (String) request.getAttribute("uploadFileError");
                request.setAttribute("workPicUploadError", uploadFileError);
                request.removeAttribute("uploadFileError"); // 临时使用，使用完毕后移除信息
                return "supplier/add";
            }
            // 将上传后的图片路径设置到属性，最终保存到数据库
            supplier.setCompanyLicPic(companyLicPicPath);
        }

        // 上传组织机构代码证
        if (orgCodePic != null) {
            String orgCodePicPath = multipartFileUpload(uploadPath, request, orgCodePic);
            if (orgCodePicPath == null) {
                String uploadFileError = (String) request.getAttribute("uploadFileError");
                request.setAttribute("workPicUploadError", uploadFileError);
                request.removeAttribute("uploadFileError"); // 临时使用，使用完毕后移除信息
                return "supplier/add";
            }
            // 将上传后的图片路径设置到属性，最终保存到数据库
            supplier.setOrgCodePic(orgCodePicPath);
        }

        // 将数据保存到数据库
        boolean flag = supplierService.add(supplier);
        logger.debug("/supplier/add " + flag + "\n" + supplier.toString());
        // 添加功能完成，跳转到列表页面
        return "redirect:/supplier/list"; // 使用重定向（让浏览器重新发起请求）
    }

    /**
     * 多部件文件上传（错误信息临时保存在request作用域uploadFileError属性中）
     *
     * @return 成功返回文件上传地址，返回null表示文件上传失败
     */
    public String multipartFileUpload(String uploadPath, HttpServletRequest request, MultipartFile multipartFile) {
        String uploadFilePath = null; // 文件上传地址，返回null表示文件上传失败

        // 定义文件存放目录
        logger.debug("上传文件路径：" + uploadPath);

        if (!multipartFile.isEmpty()) {
            // 获取上传的文件信息
            String originalFile = multipartFile.getOriginalFilename(); // 原文件名称
            logger.debug("原文件名称为：" + originalFile);
            String prefix = FilenameUtils.getExtension(originalFile); // 原文件后缀
            logger.debug("原文件后缀为：" + prefix);
            long fileSize = multipartFile.getSize(); // 原文件大小
            logger.debug("上传文件大小：" + fileSize);

            // 判断上传的文件是否符合要求
            if (fileSize > Constants.MAX_FILE_SIZE) { // 上传文件大小不能超过500KB
                request.setAttribute("uploadFileError", " * 上传文件大小不得超过 5MB");
                return uploadFilePath;
            }
            if (!(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("pneg"))) {
                request.setAttribute("uploadFileError", " * 上传文件格式只能是jpg、jpeg、png、pneg");
                return uploadFilePath;
            }

            // 确定文件存储名称
            String fileName = System.currentTimeMillis() + RandomUtils.nextInt(0, 1000) + "_Personal." + prefix;
            logger.debug("新生成的文件名为：" + fileName);

            // 将上传的文件保存到目标位置
            File targetFile = new File(uploadPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs(); // 如果目录不存在则生成目录
            }
            // 保存文件
            try {
                // 存储物理地址 + 生成的文件名称
                multipartFile.transferTo(new File(targetFile, fileName));
            } catch (IOException e) {
                e.printStackTrace();
                request.setAttribute("uploadFileError", " * 文件上传失败！");
                return uploadFilePath;
            }
            // 文件上传完成就可以拿到地址
            uploadFilePath = File.separator + Constants.UPLOAD_PATH + File.separator + fileName;
        }

        // 返回文件上传成功后的地址，失败时返回null，并且将失败信息记录到
        return uploadFilePath;
    }
}
